<html>

<head>
    <title>Upload by chunks</title>
</head>

<body>
    <input type="file" id="f" />
    <button id="u">Upload Pieces</button>
    <script src="/static/jquery.js"></script>
    <script>
        window.onload = function () {
            (function () {
                var f = document.querySelector("input#f");
                /**@param {File} thefile*/
                var thefile = null;
                f.addEventListener("change", function (event) {
                    thefile = this.files[0];
                }, false)
                var button = document.querySelector("button#u");
                button.addEventListener("click", function (event) {
                    if (thefile) {
                        let name = thefile.name;
                        let size = thefile.size;
                        let type = thefile.type;
                        jQuery.ajax({
                            url: `./chunk/uploadid?name=${name}&size=${size}&type=${type}`,
                            method: "GET",
                            success: function (data, textStatus, jqXhr) {
                                let uploadid = data['uploadid'];
                                // console.log("uploadid is ", uploadid);
                                // let piece = thefile.slice(0, 1024 * 1024 * 40);
                                // let formdata = new FormData();
                                // let xhr = new XMLHttpRequest();
                                // xhr.open("POST", `./chunk?uploadid=${uploadid}&part=1`, true);
                                // formdata.append("chunk-file", piece);
                                // xhr.send(formdata);

                                uploadInPiece(thefile, uploadid, 1024 * 1024 * 5);
                            }
                        });
                    }
                });
                function uploadInPiece(file, uploadid, piecesize = 1024 * 1024 * 4) {
                    let totalPieceCount = Math.ceil(file.size / piecesize);
                    let count = -1;//从0开始计数，一直到totalPieceCount-1
                    let go = function () {
                        let promise = new Promise((resolve, reject) => {
                            count++;
                            let start = (count * piecesize);
                            let end = start + piecesize;
                            //[start,end)
                            if (end > file.size) {
                                end = file.size;
                            }
                            console.log({ count, start, end });
                            let piece = thefile.slice(start, end);
                            let formdata = new FormData();
                            formdata.append("chunk-file", piece);
                            let xhr = new XMLHttpRequest();
                            xhr.open("POST", `./chunk?uploadid=${uploadid}&part=${count}`);
                            xhr.onabort = (event) => reject({ text: "abort", event, part: count });
                            xhr.onerror = (event) => reject({ text: "onerror", event, part: count });
                            xhr.onload = () => resolve({ text: "onload", part: count });
                            xhr.send(formdata);
                        });
                        promise.then(obj => {
                            if (count < totalPieceCount - 1) {
                                go();
                            } else {
                                console.log("all uploaded");
                                jQuery.ajax({
                                    url:`./chunk/finish?uploadid=${uploadid}`,
                                    success:function(data){
                                        console.log("data");
                                    }
                                })
                            }
                        }).catch((errorobj) => {
                            console.error("upload error", errorobj);
                            count--;
                            go();
                        });
                    };
                    go();
                }

            })();
        };
    </script>
</body>

</html>